package com.kirk.cts.ui.utils;

import com.kirk.cts.core.constants.SystemConstants;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;

/**
 * <p> MenuUtil.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-09-01 23:22
 * @Description 菜单工具类
 */
public class MenuUtil {
    /**
     * 添加主菜单
     *
     * @param muneLabel         主菜单标签
     * @param muneShortKey      主菜单快捷键
     * @param menuItemActionMap 子菜单Action，KeyStroke map对象
     *                          Action 包含子菜单标签及小图标
     *                          KeyStroke 加速键
     */
    public static JMenu createMenu(String muneLabel, String muneShortKey, Map<Action, KeyStroke> menuItemActionMap) {
        JMenu menu = new JMenu(muneLabel);
        if (StringUtils.isNotBlank(muneShortKey)) {
            menu.setMnemonic(muneShortKey.charAt(0));
        }
        if (null != menuItemActionMap) {
            Action tempAction = null;
            for (Iterator<Action> it = menuItemActionMap.keySet().iterator(); it.hasNext(); ) {
                tempAction = it.next();
                addItem(menu, tempAction, menuItemActionMap.get(tempAction));
            }
        }
        return menu;
    }

    /**
     * 添加子菜单
     *
     * @param menu          主菜单
     * @param itemAction    子菜单Action对象
     * @param itemKeyStroke 子菜单KeyStroke对象
     */
    private static void addItem(JMenu menu, Action itemAction, KeyStroke itemKeyStroke) {
        JMenuItem menuItem = new JMenuItem(itemAction);
        if (null != itemKeyStroke) {
            menuItem.setAccelerator(itemKeyStroke);
        }
        if (null != itemAction.getValue(SystemConstants.ACTION_LISTENER) && itemAction.getValue(SystemConstants.ACTION_LISTENER) instanceof ActionListener) {
            menuItem.addActionListener((ActionListener) itemAction.getValue(SystemConstants.ACTION_LISTENER));
        }
        menu.add(menuItem);
        menu.addSeparator();
    }

}
